<template>
  <div class="sidebar-container" :class="{ 'is-collapsed': isCollapsed }">
    <el-menu
      :default-active="activeMenu"
      class="sidebar-menu"
      :collapse="isCollapsed"
      :collapse-transition="false"
      :router="true"
      :unique-opened="true"
    >
      <template v-for="(item, index) in menuItems" :key="index">
        <!-- 有子菜单的菜单项 -->
        <el-sub-menu v-if="item.children && item.children.length > 0" :index="item.path">
          <template #title>
            <el-icon v-if="item.icon">
              <component :is="item.icon" />
            </el-icon>
            <span>{{ item.title }}</span>
          </template>
          
          <el-menu-item 
            v-for="(child, childIndex) in item.children" 
            :key="childIndex" 
            :index="child.path"
          >
            <el-icon v-if="child.icon">
              <component :is="child.icon" />
            </el-icon>
            <span>{{ child.title }}</span>
          </el-menu-item>
        </el-sub-menu>
        
        <!-- 没有子菜单的菜单项 -->
        <el-menu-item v-else :index="item.path">
          <el-icon v-if="item.icon">
            <component :is="item.icon" />
          </el-icon>
          <span>{{ item.title }}</span>
        </el-menu-item>
      </template>
    </el-menu>
    
    <!-- 折叠按钮 -->
    <div class="collapse-btn" @click="toggleCollapse">
      <el-icon :size="20">
        <component :is="isCollapsed ? 'Expand' : 'Fold'" />
      </el-icon>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRoute } from 'vue-router';
import { Fold, Expand } from '@element-plus/icons-vue';

// 定义组件属性
const props = defineProps({
  // 菜单项配置
  items: {
    type: Array,
    required: true
  },
  // 默认是否折叠
  defaultCollapsed: {
    type: Boolean,
    default: false
  }
});

// 获取当前路由
const route = useRoute();

// 侧边栏折叠状态
const isCollapsed = ref(props.defaultCollapsed);

// 菜单项
const menuItems = computed(() => props.items);

// 当前激活的菜单项
const activeMenu = computed(() => {
  return route.path;
});

// 切换折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};
</script>

<style scoped>
.sidebar-container {
  height: 100%;
  transition: width 0.3s;
  position: relative;
  background-color: #304156;
  width: 210px;
}

.sidebar-container.is-collapsed {
  width: 64px;
}

.sidebar-menu {
  height: 100%;
  border-right: none;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 210px;
}

.collapse-btn {
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  text-align: center;
  cursor: pointer;
  color: #bfcbd9;
  padding: 10px 0;
}

.collapse-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

/* 深度选择器修改Element Plus菜单样式 */
:deep(.el-menu) {
  border-right: none;
}

:deep(.el-menu-item.is-active) {
  background-color: #1890ff !important;
}

:deep(.el-menu-item:hover),
:deep(.el-sub-menu__title:hover) {
  background-color: #263445 !important;
}
</style>